define(function(require, exports, module){
	
	/**
     * @name popChart
     * @class 封装报表弹出框。
     */
	var tmpl = ['<div class="pop-showchart">',
		    		'<div class="title left"><span class="name"></span>{title}</div>',
		    		'<div class="daterangebox pull-right">',
		    	        '<input type="text" name="chartdate" class="daterangebox-ipt" placeholder="按周期模糊搜索" readonly />',
		    	        '<a class="daterangebox-btn" href="javascript:;">日期</a>',
		    	    '</div>',
		    		'<div class="dropbox pull-right">',
		    			'<input class="changelist" name="changelist" placeholder="切换媒体" style="display:none;"/>',
	    			'</div>',
	    			'<div class="dropbox pull-right typebox">',
		    		    '<select name="type" style="width:140px;" placeholder="按媒体类型搜索">',
		    				'<option value="">全部媒体</option>',
		    				'<option value="1">站外</option>',
		    				'<option value="0">站内</option>',
		    				'<option value="2">联盟</option>',
		    			'</select>',
		    	    '</div>',
		    	    '<div class="chartbox pull-left">',
			    		'<div class="popchart"></div>',
			    		'<div class="datatype">',
			    			'<label><input type="radio" name="datatype" value="pv" checked="checked">曝光量</label>',
			    			'<label><input type="radio" name="datatype" value="uv">独立访客量</label>',
			    			'<label><input type="radio" name="datatype" value="click">点击量</label>',
			    			'<label><input type="radio" name="datatype" value="ctr">点击转化率</label>',
			    			'<label><input type="radio" name="datatype" value="cost">媒体花费</label>',
							'<label><input type="radio" name="datatype" value="sale_income">预售花费</label>',
			    			'<label><input type="radio" name="datatype" value="bid">竞价收入</label>',
			    			'<label><input type="radio" name="datatype" value="sale_income">预售收入</label>',
			    			'<label><input type="radio" name="datatype" value="profit">净收益</label>',
			    		'</div>',
			    	'</div>',
			    '</div>'].join('');
	
    
    var popchart = function(option){
    	var op = $.extend({
    			title: '',
	    		btn: $('.showchart'),
	    		dataurl: '',
	    		idname: '',
	    		idvalue: '',
	    		other: {},
	    		start: semi.daterange.start,
	    		end: semi.daterange.end,
	    		hastype: false
	    	},option), popChart;
    	
    	if(semi.utils.isEmpty(op.dataurl))return;
    	
		var $dlg = $dialog({
		    width: '800px',
		    onshow: function() {
		    	var $d = this, $node = $($d.node);
		    	var refreshDialog = function(){
		    			//$('.name',$node).text($('[name=changelist] :checked',$node).text());
	    	        	$('[name=datatype][value=pv]',$node)[0].checked = true;
	    	        	popChart.clear().setOption({
	    		            tooltip: {
	    		                trigger: 'axis',
	    		                axisPointer: {
	    		                	type : 'line',
	    		                	lineStyle : {
	    		                	  color: '#cccccc',
	    		                	  width: 1,
	    		                	  type: 'solid'
	    		                	}
	    	                	},
	    	                	formatter: function (params) {
	    	                		try{
	    	                			if(params[0][0].trim()=='点击转化率'){
	    	                				return params[0][1]+'<br/>'+params[0][0]+': '+params[0][2] + '‰'
	    	                			}
	    	            			}catch(e){}
	    	                		return params[0][1]+'<br/>'+params[0][0]+': '+params[0][2]
	    	                	}
	    		            },
	    		            legend: {
	    		            	orient:'vertical',
	    		                data:['曝光量']
	    		            },
	    		            grid: {
	    		            	y: 30,
	    		            	y2: 30
	    		            },
	    		            xAxis: {
	    		                type: 'category',
	    		                boundaryGap: false,
	    		                data: chartData.date,
	    		                axisLine:{
	    		                	show: true,
	    		                	lineStyle: {
	    		                        color: '#cccccc', 
	    		                        width: 1
	    		                    }
	    		                },
	    		                axisLabel:{
	    		                	textStyle:{
	    		                		color: '#ababab'
	    		                	}
	    		                },
	    		                splitLine: {
	    		                    show: true,
	    		                    lineStyle: { 
	    		                        color: '#ebebeb',
	    		                        width: 1
	    		                    }
	    		                },
	    		                boundaryGap: [0.1,0.1]
	    		            },
	    		            yAxis: {
	    		                type: 'value',
	    		                axisLine:{
	    		                	show: true,
	    		                	lineStyle: {
	    		                        color: '#cccccc', 
	    		                        width: 1
	    		                    }
	    		                },
	    		                axisLabel:{
	    		                	textStyle:{
	    		                		color: '#ababab'
	    		                	},
	    		                	formatter: function (params) {
	    		                		try{
	    		                			var _name = popChart.getOption().legend.data[0].trim();
	    		                			if(_name=='点击转化率'){
	    		                				return params + '‰'
	    		                			}
	    	                			}catch(e){}
	    		                		return params
	    		                	}
	    		                },
	    		                splitArea: {
	    		                	show: true,
	    		                	areaStyle: {color: ['#ffffff','#f6f6f6']}
	    		                },
	    		                splitLine: {
	    		                    show: true,
	    		                    lineStyle: { 
	    		                        color: '#ebebeb',
	    		                        width: 1
	    		                    }
	    		                },
	    		                boundaryGap: [0.1,0.1]
	    		            },
	    		            /*toolbox: {
	    		                show : true,
	    		                feature : {
	    		                    magicType : {show: true, type: ['line', 'bar']},
	    		                    saveAsImage : {show: true}
	    		                },
	    		                x: 550
	    		            },*/
	    		            series: [
	    						{
	    						    name:'曝光量',
	    						    type:'line',
	    						    data:chartData.pv
	    						}
	    		            ]
	    		        });
	    	        };
		        
				getChartData(op.dataurl, $.extend({
		    		start: op.start,
		    		end: op.end
		    	}, semi.utils.newObj(op.idname, op.idvalue), op.other), function(data){
					
		    		//列表切换
		    		var datas = [], _tmpl = tmpl;
		    		if(op.type=='media'){
		    			datas = data.media;
		    		}else if(op.type=='position'){
		    			datas = data.positions;
		    		}else if(op.type=='strategy'){
		    			datas = data.positions;
		    			_tmpl = _tmpl.replace('<label><input type="radio" name="datatype" value="bid">竞价收入</label>','');
		    		}else if(op.type=='resource'){
		    			_tmpl = _tmpl.replace('<label><input type="radio" name="datatype" value="bid">竞价收入</label>','');
		    		}
					
		    		//非admin隐藏收益数据
		    		try{
		    			if(admin=='False'){
		    				_tmpl = _tmpl.replace('<label><input type="radio" name="datatype" value="profit">净收益</label>','')
		    							 .replace('<label><input type="radio" name="datatype" value="sale_income">预售收入</label>','')
		    			}
		    			if(merchant == 'True' || vendor == 'True'){
		    				if(op.type=='strategy'){
		    					_tmpl = _tmpl.replace('媒体花费','竞价花费')
		    				}else if(op.type=='resource'){
		    					_tmpl = _tmpl.replace('<label><input type="radio" name="datatype" value="cost">媒体花费</label>','')
		    								 .replace('<label><input type="radio" name="datatype" value="sale_income">预售花费</label>','')
		    				}
		    			}else{
		    				_tmpl = _tmpl.replace('<label><input type="radio" name="datatype" value="sale_income">预售花费</label>','')
		    				if(op.type=='resource'){
		    					_tmpl = _tmpl.replace('<label><input type="radio" name="datatype" value="cost">媒体花费</label>','')
		    				}
		    			}
		    			/*if(platform == "True"){
		    				_tmpl = _tmpl.replace('<label><input type="radio" name="datatype" value="cost">媒体花费</label>','')
		    			}*/
		    		}catch(e){}
		    		
		    		$d.content(_tmpl.replaceAll('{title}', op.title));
		    		
		    		//是否支持按媒体类型搜索
		    		if(!op.hastype){
		    			$('.typebox',$node).remove();
		    		}else{
		    			$('.typebox select',$node).on('change', function(){
		    				var type = $(this).val(), 
		    					date = $('.daterangebox-ipt',$node).val().split(' 至 ');
		    				
		    	        	var _data = [{id:-1, text:'全部媒体'}];
			    			$.each($('[name=changelist]',$node).data('data'), function(i,n){
			    				if(type=='' || n.type==type)_data.push({id:n.id, text:n.name});
			    			});
			    			$('[name=changelist]',$node).select2({data:_data}).select2('val', -1);
			    			
		    				getChartData(op.dataurl, $.extend({
		    					start: date[0],
		    					end: date[1],
		    					type: type
		    				}, semi.utils.newObj(op.idname, -1), op.other),refreshDialog);
		    			}).select2();
		    		}
		    		
		    		if(!semi.utils.isEmpty(datas)){
		    			var _data = [{id:-1, text:'全部媒体'}];
		    			$.each(datas, function(i,n){
		    				_data.push({id:n.id, text:n.name});
		    			});
		    			$('[name=changelist]',$node).show().select2({data:_data}).on('change', function(){
		    				var value = $(this).val(), date = $('.daterangebox-ipt',$node).val().split(' 至 ');
		    				
		    				getChartData(op.dataurl, $.extend({
		    					start: date[0],
		    					end: date[1]
		    				}, semi.utils.newObj(op.idname, value), op.other, (op.hastype?{type:$('[name=type]',$node).val()}:{})),refreshDialog);
		    			}).select2('val', op.idvalue).data('data',datas);
		    		}
		    		
		    		//初始化图标
	    	        popChart = echarts.init($('.popchart',$node)[0]);
	    	        $('.daterangebox-ipt',$node).val(op.start + ' 至 ' + op.end).daterangepicker({
	    	        	opens: 'left',
	    	        	initStart: op.start,
	    	        	initEnd: op.end,
	    	            format:'YYYY-MM-DD',
	    	            maxDate: moment().subtract('days', 1).format("YYYY-MM-DD")
	    	        }, function(start, end, label) {
	    	        	var idvalue = $('[name=changelist]',$node).val();
	    	        	if(semi.utils.isEmpty(idvalue))idvalue = op.idvalue;
	    				getChartData(op.dataurl, $.extend({
	    					start: start.format('YYYY-MM-DD'),
	        	    		end: end.format('YYYY-MM-DD')
	    		    	}, semi.utils.newObj(op.idname, idvalue), op.other, (op.hastype?{type:$('[name=type]',$node).val()}:{})),refreshDialog);
	    	        });
	    	        
	    			$('[name=datatype]',$node).on('change', function(){
	    				var type = $(this).val(), name = $(this).parent().text();
	    				popChart.setOption({
	        	            legend: {
	        	                data:[name]
	        	            },
	        	            series: [{
	    					    name:name,
	    					    data:chartData[type]
	        				}]
	        	        });
	    			});
		    		$node.initUI(refreshDialog);
		    	});
		    },
		    cancelValue: '关闭',
		    cancel: true
		}).showModal();
	}
    
    /* 获取报表数据 */
    var chartData = {pv:[], uv:[], click:[], ctr:[], cost:[], bid:[], profit:[], sale_income:[], date:[]};
    var getChartData = function(url, params, callback){
    	$ajax.ajax({
    		url: url,
    		data: params,
    		//url: '/trp/media/report?media_id=1&org_id=1&start='+params.start+'&end='+params.end,
    		success: function(data){
    			var days = moment(params.end).diff(moment(params.start), 'days')+1;
    			seajs.log('获取 '+days+' 天数据！')
    			
    			chartData = {pv:[], uv:[], click:[], ctr:[], cost:[], bid:[], profit:[], sale_income:[], date:[]};
    			var s = params.start;
    			for(var i=0; i<days; i++){
    				chartData.pv.push(0);
    				chartData.uv.push(0);
    				chartData.click.push(0);
    				chartData.ctr.push(0);
    				chartData.cost.push(0);
    				chartData.bid.push(0);
    				chartData.profit.push(0);
    				chartData.sale_income.push(0);
    				chartData.date.push(s);
    				s = moment(s).add('days', 1).format('YYYY-MM-DD');
    			}
    			
    			if(!semi.utils.isEmpty(data) && !semi.utils.isEmpty(data.data)){
    				$.each(data.data, function(i,n){
    					var index = chartData.date.indexOf(n.date);
    					
    					chartData.pv[index] = n.pv || 0;
    					chartData.uv[index] = n.uv || 0;
    					chartData.click[index] = n.click || 0;
    					chartData.ctr[index] = n.ctr || 0;
    					chartData.cost[index] = n.cost || 0;
    					chartData.bid[index] = n.bid || 0;
    					chartData.profit[index] = n.profit || 0;
    					chartData.sale_income[index] = n.sale_income || 0;
    				});
    			}
    			seajs.log(chartData);
    			if(!semi.utils.isEmpty(callback) && $.isFunction(callback))callback.call(this, data);
    		},
    		error: function(data){
    			seajs.log('获取报表数据出错，请检查参数配置信息！');
    		}
    	});
    }
    
    return popchart;
});